package com.danbay.framework.utils;

import java.text.DecimalFormat;
import java.util.UUID;

public class StringUtils extends org.apache.commons.lang3.StringUtils{
	
	public StringUtils(){}
	
	
	/***
	 *  以四舍五入的方式格式化为字符串
	 * @param obj 数值
	 * @param format 格式,如.00即保留2位小数
	 */
	public static String numberFormat(Object obj,String format){
		String str="0.00";
		try {
			if(null==format||"".equals(format.trim())){
				format="##########0.00";
			}
			
			DecimalFormat dataFormat = new DecimalFormat(format);
			str=dataFormat.format(obj);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return str;
	}

	/**
	 * 格式化字符串：<br/>
	 * 如：format("a{0}b{1}","xx","yy")<br/>
	 * 结果：axxbyy
	 * @param val
	 * @param args
	 * @return
	 */
	public static String format(String val,Object... args){
		for(int i=0; i< args.length; i++){
			val=val.replace("{"+i+"}","%"+(i+1)+"$s");
		}
		return String.format(val, args);
	}
	
	/**
	 * 32位无-的全局唯一ID
	 * @return
	 */
	public static String newUUID(){
		return UUID.randomUUID().toString().replace("-", "");
	}

	/**
	 * 字节码转16进制字符串
	 * @param src 源字节码
	 * @return 16进制字符串
	 */
	public static String bytesToHexString(byte[] src){
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	/**
	 * Convert hex string to byte[]
	 * @param hexString the hex string
	 * @return byte[]
	 */
	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}
	
	/**
     * 生成设备id
     *
     * @param mac 设备mac或唯一码长度不超过16位（不包含非数字和字母）
     *            规则：12位的(yyyyMMddHHmmss)16进制串+mac,mac小于16位时后面补0
     * @return 32位id
     */
    public static String generateDeviceId(String mac) {
        //取yyyyMMddHHmmss的16进制串
        String timeStr = DateUtils.now(DateUtils.YMDHMS2);
        Long timeLong = Long.parseLong(timeStr);
        timeStr = Long.toHexString(timeLong);
        //去除非数字和字母的字符
        mac = mac.replaceAll("[^0-9A-Za-z]", "").toLowerCase();
        //使用0填充到20位
        mac = StringUtils.rightPad(mac, 32 - timeStr.length(), '0');
        //12+20
        return timeStr + mac;
    }
	
	/**
	 * Convert char to byte
	 * @param c char
	 * @return byte
	 */
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}
}
